#!/usr/bin/env python
# encoding: utf-8

from django.views.generic.edit import FormView
from account.user import forms
from django.contrib.auth import authenticate, login, logout
from django.http import HttpResponseRedirect
from django.urls import reverse
from django.views import View
from django.views.generic import  ListView
from django.contrib.auth.models import User,Group,Permission
from django.contrib.auth.mixins import LoginRequiredMixin
from dashboard.common.utiles import get_pagerange


import logging
logger = logging.getLogger("myself")


# 用户登录
class UserLoginView(FormView):
    template_name = "login.html"
    # success_url = '/dashboard'
    form_class = forms.LoginForm
    def form_valid(self, form):
            data = form.cleaned_data
            user = authenticate(username=data['username'], password=data['password'])
            if user is not None:
                login(self.request,user)
                logger.debug("登录成功"+ data['username'])
                return HttpResponseRedirect(reverse('index'))
                # return super(ContactView, self).form_valid(form)
            else:
                logger.debug("账号或密码不正确"+str(data))
                return HttpResponseRedirect(reverse('login'))

# 用户退出类
class UserLogoutView(View):
    def get(self, request):
        logout(request)
        return HttpResponseRedirect(reverse("login"))


#  显示用户信息
class UserListView(LoginRequiredMixin, ListView):
    template_name = "userlist.html"
    model = User
    # context_object_name = "user_objects"
    paginate_by = 12
    ordering = "id"

    # 自定义变量，显示的前后分页数量
    before_range_num = 4
    after_range_num = 4


    def get_queryset(self):
        queryset = super(UserListView, self).get_queryset()
        # 不显示超级管理员信息
        queryset = queryset.filter(is_superuser=False)
        # 获取查询参数
        username = self.request.GET.get("search_username", None)
        if username:
            # username__icontains=username 查询包含有username的所有用户数据
            queryset = queryset.filter(username__icontains=username)
        return queryset


    def get_context_data(self, **kwargs):
        context = super(UserListView, self).get_context_data(**kwargs)
        context['page_range'] = get_pagerange(context['page_obj'],self.before_range_num,self.after_range_num)
        context['search_data']=""
        logger.debug(context)
        return context

# 新增用户
class UserAddView(FormView):
    template_name = "useradd.html"
    form_class = forms.UserAddForm
    def form_valid(self, form):
        return HttpResponseRedirect(reverse('user_list'))


# 显示权限信息
class PermissionListView(ListView):
    model = Permission
    template_name = "permissionlist.html"